package com.glink.manage.service.Impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glink.manage.dto.ai.AiTaskDTO;
import com.glink.manage.vo.ai.AiVO;
import com.glink.manage.service.AiService;
import com.glink.manage.vo.ai.ResultDetailVO;
import com.glink.manage.vo.ai.ResultValueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.glink.manage.common.enums.AiCodeDict;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AiServiceImpl implements AiService {

    @Autowired
    private RestTemplate restTemplate;  // 用于发送 HTTP 请求

    @Value("${image.ai_task.url:}")
    private String imageTaskUrl;  // 算法服务的URL在配置里

    /**
     * 算法请求体
     * @param aiTaskDTO 请求的AI任务数据
     * @return 算法结果信息
     */
    @Override
    public AiVO invokeAlgorithm(AiTaskDTO aiTaskDTO) {

        try {
            // 发送 HTTP 请求到外部算法服务
            String resultData = restTemplate.postForObject(imageTaskUrl, aiTaskDTO, String.class);
            // 解析算法返回的数据，并返回 VO
            return parseAlgorithmResponse(resultData);
        }catch (Exception e){
            log.error("算法分析请求失败，imageTaskUrl：{}, analyseId:{}", imageTaskUrl, aiTaskDTO.getAnalyseId(), e);
            return new AiVO(AiCodeDict.ERROR.getKey(), aiTaskDTO.getAnalyseId());
        }
    }

    @Override
    public AiVO invokeAlgorithm(String analyseId, String imageBase64Data) {
        return invokeAlgorithm(new AiTaskDTO(analyseId, imageBase64Data));
    }
    
    private AiVO parseAlgorithmResponse(String resultData) {
        if (resultData == null || resultData.trim().isEmpty()) {
            throw new RuntimeException("返回数据为空");
        }
        
        log.debug("AI算法分析返回数据：{}", resultData);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode resultNode;
        try {
            resultNode = objectMapper.readTree(resultData);
        } catch (IOException e) {
            throw new RuntimeException("解析算法返回的 JSON 时出错: " + e.getMessage(), e);
        }

        // 提取 resultCode 字段并检查
        String resultCodeStr = resultNode.path("resultCode").asText();
        AiVO aiVO = new AiVO();
        aiVO.setResultCode(resultCodeStr);
        aiVO.setAnalyseId(resultNode.path("analyseId").asText());

        JsonNode resultValueNode = resultNode.path("resultValue");
        if (resultValueNode.isMissingNode() || resultValueNode.isNull()) {
            // 处理 resultValue 为空的情况
            aiVO.setResultValue(null); // 或者可以设置一个空的 ResultValueVO 实例
            return aiVO; // 返回当前对象，表明算法未识别出结果
        }

        ResultValueVO resultValueVO = new ResultValueVO();

        // 分析结果描述列表
        List<String> analyseResults = objectMapper.convertValue(resultValueNode.path("analyseResults"), new TypeReference<List<String>>() {
        });
        resultValueVO.setAnalyseResults(analyseResults);

        // 详细结果
        List<ResultDetailVO> resultDetails = new ArrayList<>();
        JsonNode resultDetailNode = resultValueNode.path("resultDetail");
        if (resultDetailNode.isArray()) {
            for (JsonNode detail : resultDetailNode) {
                ResultDetailVO resultDetailVO = new ResultDetailVO();
                resultDetailVO.setAlgCode(detail.path("algCode").asText());
                resultDetailVO.setNum(detail.path("num").asInt());
                resultDetailVO.setResultItems(detail.path("resultItems").toString()); // 直接转换为字符串
                resultDetailVO.setResultDesc(detail.path("resultDesc").asText());
                resultDetails.add(resultDetailVO);
            }
        }
        resultValueVO.setResultDetails(resultDetails);

        // 处理后的图片base64编码
        resultValueVO.setOsdImageData(resultValueNode.path("osdImageData").asText());

        // OSD图像名称
        resultValueVO.setOsdImageName(resultValueNode.path("osdImageName").asText());

        // 分析时间
        resultValueVO.setAnalyseTime(resultValueNode.path("analyseTime").asText());

        aiVO.setResultValue(resultValueVO);

        return aiVO;
    }
}
